#!/usr/bin/python
# -*- coding: UTF-8 -*-

#! encoding = utf-8

import os, sys, time, logging
from lib.uploadmedia import Upload
import urllib.request
import urllib.parse
import json

if __name__ == "__main__":
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    logging.basicConfig(filename='log/upload/main.log', level=logging.WARNING, format=LOG_FORMAT)

    url = 'http://192.168.31.26:8080/api/getReadyTask'
    report_url = 'http://192.168.31.26:8080/api/report/{0}/{1}'
    while True:
        f = urllib.request.urlopen(url)
        ddict = json.loads(f.read().decode('utf-8'))
        #print(ddict)
        if (ddict['status'] == 1):
            logging.warning(ddict)
            try:
                device = Upload(ddict['device_id'])
                if device.start(ddict['path'], ddict['title'], ddict['app_id']):
                    urllib.request.urlopen(report_url.format(ddict['id'], 'success'))
                else:
                    urllib.request.urlopen(report_url.format(ddict['id'], 'error'))
            except Exception as e:
                logging.warning(e)
                urllib.request.urlopen(report_url.format(ddict['id'], 'error'))
            else:
                urllib.request.urlopen(report_url.format(ddict['id'], 'success'))

        logging.warning("睡眠5s继续执行")
        time.sleep(5)


